package com.gaogzhen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaogzhen.domain.SysUser;
import com.gaogzhen.domain.SysUserRole;
import com.gaogzhen.mapper.SysUserMapper;
import com.gaogzhen.service.SysUserRoleService;
import com.gaogzhen.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.NotBlank;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService{

    @Autowired
    private SysUserRoleService sysUserRoleService;



    @Override
    public Page<SysUser> findByPage(Page<SysUser> page, String mobile, String fullname) {
        // 查询用户
        Page<SysUser> userPage = page(page, new LambdaQueryWrapper<SysUser>()
                .like(StringUtils.isNotBlank(mobile), SysUser::getMobile, mobile)
                .like(StringUtils.isNotBlank(fullname), SysUser::getFullname, fullname));
        // 查询用户对应的角色
        List<SysUser> users = userPage.getRecords();
        if (!CollectionUtils.isEmpty(users)) {
            for (SysUser user : users) {
                String roleString = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>()
                        .eq(SysUserRole::getUserId, user.getId())
                        ).stream()
                        .map(s -> s.getRoleId().toString())
                        .collect(Collectors.joining(","));
                user.setRole_strings(roleString);

            }
        }
        userPage.setRecords(users);
        return userPage;
    }

    @Override
    @Transactional
    public boolean deleteUsersByIds(Long[] ids) {

        List<Long> idList = Arrays.asList(ids);
        // 1、移除用户角色中间表数据
        for (Long id : idList) {
            boolean remove = sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>()
                    .eq(SysUserRole::getUserId, id));
            if (!remove) {
                throw new ApiException("删除用户角色失败!");
            }
        }
        // 2、移除用户表数据
        boolean b = removeByIds(idList);
        if (!b) {
            throw new ApiException("删除用户失败!");
        }
        return true;
    }

    @Override
    @Transactional
    public boolean add(SysUser sysUser) {
        // 加密密码
        @NotBlank String password = sysUser.getPassword();
        String encode = new BCryptPasswordEncoder().encode(password);
        sysUser.setPassword(encode);
        boolean save = save(sysUser);
        if (!save) {
            throw new ApiException("添加用户失败!");
        }
        // 设置角色
        String roleStrings = sysUser.getRole_strings();
        if (StringUtils.isNotBlank(roleStrings)) {
            Long userId= sysUser.getId();
            String[] roleIds = roleStrings.split(",");
            List<SysUserRole> sysUserRoleList = Stream.of(roleIds).map(id -> {
                Long roleId = Long.valueOf(id);
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(roleId);
                sysUserRole.setUserId(userId);
                return sysUserRole;
            }).collect(Collectors.toList());
            boolean b = sysUserRoleService.saveBatch(sysUserRoleList);
            if (!b) {
                throw new ApiException("批量添加用户角色失败!");
            }

        }
        return true;
    }

    @Override
    public boolean updateUser(SysUser sysUser) {
        // 修改用户信息
        updateById(sysUser);
        // 修改用户角色
        Long userId = sysUser.getId();
        // 删除用户原有的角色
        sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, userId));

        // 设置新的用户角色
        String roleStrings = sysUser.getRole_strings();
        if (StringUtils.isNotBlank(roleStrings)) {
            String[] roleIds = roleStrings.split(",");
            List<SysUserRole> sysUserRoleList = Stream.of(roleIds).map(id -> {
                Long roleId = Long.valueOf(id);
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(roleId);
                sysUserRole.setUserId(userId);
                return sysUserRole;
            }).collect(Collectors.toList());
            boolean b = sysUserRoleService.saveBatch(sysUserRoleList);
            if (!b) {
                throw new ApiException("批量添加用户角色失败!");
            }

        }
        return true;
    }
}
